package com.lisn.springfileuploaddownloadserver;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

@Controller
public class SGUploadController {
    private static final String utf8 = "utf-8";

    @RequestMapping("/uploadsg")
    @ResponseBody
    public void upload(HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding(utf8);
        Integer schunk = null;
        Integer schunks = null;
        String name = null;
        String uploadPath = "D:\\fileItem";
        BufferedOutputStream outputStream = null;
        System.out.println("---------------1");

        try {
            if (ServletFileUpload.isMultipartContent(request)) {
                try {
                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    factory.setSizeThreshold(1024);
                    factory.setRepository(new File(uploadPath));// 设置临时目录
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    upload.setHeaderEncoding("UTF-8");
                    upload.setSizeMax(5 * 1024 * 1024 * 1024);// 设置附近大小
                    List<FileItem> items = upload.parseRequest(request);

                    System.out.println("items size "+items.size());
                    System.out.println("---------------2");

                    // 生成新文件名
                    String newFileName = null;
                    for (FileItem item : items) {
                        if (!item.isFormField()) {// 如果是文件类型
                            name = newFileName;// 获得文件名
                            if (name != null) {
                                String nFname = newFileName;
                                if (schunk != null) {
                                    nFname = schunk + "_" + name;
                                }
                                File savedFile = new File(uploadPath, nFname);
                                item.write(savedFile);
                            }
                        } else {
                            // 判断是否带分割信息
                            if (item.getFieldName().equals("chunk")) {
                                schunk = Integer.parseInt(item.getString(utf8));
                                System.out.println("schunk = " + schunk);
                            }
                            if (item.getFieldName().equals("chunks")) {
                                schunks = Integer.parseInt(item.getString(utf8));
                                System.out.println("schunks = " + schunks);
                            }

                            if (item.getFieldName().equals("name")) {
                                newFileName = new String(item.getString(utf8));
                                System.out.println("newFileName = " + newFileName);
                            }
                        }
                    }
                    System.out.println(schunk + "/" + schunks);
                    if (schunk != null && schunk == 1) {
                        // TfileUploadStatus file = statusService.get(newFileName);
                        // if (file != null) {
                        //     statusService.updateChunk(newFileName, schunk);
                        // } else {
                        //     statusService.add(newFileName, schunk, schunks);
                        // }

                    } else {
                        // TfileUploadStatus file = statusService.get(newFileName);
                        // if (file != null) {
                        //     statusService.updateChunk(newFileName, schunk);
                        // }
                    }
                    if (schunk != null && schunk.intValue() == schunks.intValue()) {
                        outputStream = new BufferedOutputStream(new FileOutputStream(new File(uploadPath, newFileName)));
                        // 遍历文件合并
                        for (int i = 1; i <= schunks; i++) {
                            System.out.println("文件合并:" + i + "/" + schunks);
                            File tempFile = new File(uploadPath, i + "_" + name);
                            byte[] bytes = FileUtils.readFileToByteArray(tempFile);
                            outputStream.write(bytes);
                            outputStream.flush();
                            tempFile.delete();
                        }
                        outputStream.flush();
                    }
                    response.getWriter().write("{\"status\":true,\"newName\":\"" + newFileName + "\"}");
                } catch (FileUploadException e) {
                    e.printStackTrace();
                    response.getWriter().write("{\"status\":false}");
                } catch (Exception e) {
                    e.printStackTrace();
                    response.getWriter().write("{\"status\":false}");
                } finally {
                    try {
                        if (outputStream != null)
                            outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
